﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Model_SSResourceManager
{
    class MessageDataContext : ItemDataContext<Message, MESSAGE>
    {
        public MessageDataContext()
        {
            EntitySetName = "MESSAGES";
        }

        public List<Message> GetActiveMessages(Guid? _userId = null)  // if set _userId - select not sended only for this user
        {
            List<Message> _retList = new List<Message>();

            using (SSRMDBEntities context = new SSRMDBEntities())
            {
                try
                {
                    Message modelItem;
                    var NotSendedMessages =from entMessage in context.MESSAGES
                                                  where !entMessage.SendOk 
                                                  select entMessage;
                    if ( _userId !=null )
                        NotSendedMessages = from entMessage in NotSendedMessages 
                                            where entMessage.UserId == _userId 
                                            select entMessage;

                    foreach (MESSAGE entItem in NotSendedMessages)
                    {
                        modelItem = new Message();
                        EntityToModel(entItem, modelItem);
                        _retList.Add(modelItem);
                    }
                }
                catch (Exception ex)
                {
                    OnRaiceDbErrEvent(new DbErrEventArgs(ex.Message));
                }
            }

            return _retList;
        }

        protected override void EntityToModel(MESSAGE _entMessage, Message _Message)
        {
            _Message.Id = _entMessage.Id;
            _Message.UserId = _entMessage.UserId;
            _Message.MessageText = _entMessage.MessageText;
            _Message.CreateTime = _entMessage.CreateTime;
            _Message.SendedEmail = _entMessage.SendedEmail;
            _Message.SendedSkype = _entMessage.SendedSkype ;
            _Message.EmailOk = _entMessage.EmailOk;
            _Message.SkypeOk = _entMessage.SkypeOk;            
        }

        protected override void ModelToEntity(Message _Message, MESSAGE _entMessage)
        {
            _entMessage.Id = _Message.Id;
            _entMessage.UserId = _Message.UserId;
            _entMessage.MessageText = _Message.MessageText;
            _entMessage.CreateTime = _Message.CreateTime;
            _entMessage.EmailOk = _Message.EmailOk;
            _entMessage.SkypeOk = _Message.SkypeOk;
            _entMessage.SendedEmail  = _Message.SendedEmail ;
            _entMessage.SendedSkype  = _Message.SendedSkype ;
            _entMessage.SendOk  = _Message.SendOk;
        }
    }
}
